<template>
  <div>
    <van-uploader
        v-model="fileList"
        :action="url"
        accept="image/*"
        :data="{ phone: phone}"
        :before-upload="beforeUpload"
        :after-read="afterRead"
    >
      <img
          class="avatar"
          src="https://img01.yzcdn.cn/vant/apple-1.jpg">
<!--          @click="handleAvatarClick"-->
<!--      />-->
<!--      <van-icon
          class="avatar"
          name="photo-o"
          @click="handleAvatarClick"
      />-->
    </van-uploader>
  </div>
</template>
<script>
export default {
  inject: ['$apiUrl', '$headImgUrl'],
  data() {
    return {
      avatarUrl: ' ', // 初始头像 URL
      fileList: [],
      phone: '', // 当前用户ID
      url: this.$apiUrl + '/user/upload'
    };
  },
  methods: {
/*    handleAvatarClick() {
      // 打开文件选择器
      console.log("打开文件选择器")
      this.$refs.uploader.chooseFile();
    },*/
    beforeUpload(file) {
      // 限制上传文件的大小和类型
      console.log("限制上传文件的大小和类型")
      const isLt2M = file.size / 1024 / 1024 < 2;
      const isImage = /^image\//.test(file.type);
      if (!isLt2M) {
        this.$toast('上传头像图片大小不能超过 2MB');
        return false;
      }
      if (!isImage) {
        this.$toast('请上传头像图片');
        return false;
      }
      console.log("允许发送请求")
      return true;
    },
    async afterRead(file) {
      const formData = new FormData();
      formData.append('file', file.file);
      formData.append('phone', this.phone);

      try {
        // const url = this.$apiUrl + '/upload';
        console.log("发送请求")
        const response = await this.$http.post(this.url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
        });

        if (response.status === 200) {
          console.log("请求成功")
          console.log(response.data.data.url)
          const avatarUrl = response.data.avatarUrl;
          this.avatarUrl = avatarUrl;

          // 将上传成功的文件信息存储到 fileList 中，以便后续操作
          this.fileList.push({
            url: avatarUrl,
            name: file.file.name,
          });
        } else {
          console.log("请求失败")
          this.$toast(response.data.message || '上传头像失败');
        }
      } catch (error) {
        console.error(error);
        this.$toast('上传头像失败，请稍后再试');
      }
    },
    getUserByPhone(){
      const registerDTO = {
        phone: this.phone
      }
      const url = this.$apiUrl + '/user/getUserByPhone';
      this.$http.post(url, registerDTO).then(res => {
        console.log(res.data.data.mobile)
        console.log(res.data.data.username)
      })
    }
  },
  created() {
    this.phone = localStorage.getItem("username");
    this.getUserByPhone()
  }
};
</script>

<style scoped>
.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}
</style>
